package cn.lcfms.app.admin.controller;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.lcfms.app.admin.bean.AdminBean;
import cn.lcfms.app.admin.bean.GroupBean;
import cn.lcfms.bin.App;
import cn.lcfms.bin.Permission;
import cn.lcfms.bin.PermitPoll;
import cn.lcfms.bin.Userinfo;
import cn.lcfms.service.BaseService;
import cn.lcfms.unit.Encrypt;



@PermitPoll(type="系统管理",name="用户管理",forward="login.html")
@Controller("admin.User")
@RequestMapping("/admin/user")
public class User extends BaseController {
	/*
	 * 增加用户组页面
	 */
	@RequestMapping("/add_group_view")
	public String add_group_view(HttpServletRequest request,GroupBean group){
		Xmllist xlist=this.getPermissionList();
		request.setAttribute("permission_action", xlist.permission_action);
		request.setAttribute("permission_type_action", xlist.permission_type_action);
		if(group.getGid()!=0){
			BaseService service = App.getService("group");	
			group=service.selectOne(GroupBean.class,group.getGid());
			Xmllist x=this.getPermissionList();
			request.setAttribute("GroupPermission", group.getGpermission().split(","));
			request.setAttribute("permission_action", x.permission_action);
			request.setAttribute("permission_type_action", x.permission_type_action); 
		}
		request.setAttribute("group", group);
		return "admin/frame/groupAdd";
	}
	/*
	 * 查看用户组界面
	 */
	@RequestMapping("/manage_group")
	public String manage_group(HttpServletRequest request) throws Exception{
		if(Permission.PERMIT==null){
			Permission.PERMIT=new ArrayList<HashMap<String, Object>>();
			Permission permission=Permission.getpermission();;
        	permission.initialize();
        	permission.set_permission(); 	
    	}   
		BaseService service = App.getService("group");			
		List<HashMap<String, Object>> list = service.selectList();
		request.setAttribute("list", this.getGroupPermission(list));		
		return "admin/frame/groupManage";
	}
    /*
     * 处理修改或增加用户组
     */
	@RequestMapping("/add_group")
	public String add_group(String[] gpermission,GroupBean bean){
		BaseService service = App.getService("group");
		if(bean.getGid()!=0){
			String g1=StringUtils.join(gpermission,",");
			bean.setGpermission(g1);
			service.update(bean);
		}else{
			String g1=StringUtils.join(gpermission,",");
			bean.setGpermission(g1);
			service.insert(bean);
		}
		return "local:manage_group";
	}
	/*
	 * 删除用户组
	 */
	@RequestMapping("/delete_group")
	public String delete_group(int gid){
		BaseService service = App.getService("group");
		service.deleteById(gid);
		return "local:manage_group";
	}
	/*
	 * 增加或修改用户界面
	 */
	@RequestMapping("/add_update_view")
	public ModelAndView update_user_view(AdminBean bean){
		BaseService service = App.getService("group");
		List<HashMap<String, Object>> list = service.selectList();
		ModelAndView view=new ModelAndView("admin/frame/userAdd","list",list);
		if(bean.getAid()!=0){			
			bean=service.setTable("admin").selectOne(AdminBean.class, bean.getAid());		
		}
		view.addObject("user", bean);
		return view;
	}
	/*
	 * 查看用户界面
	 */
	@RequestMapping("/manage_user")
	public ModelAndView manage_user(){	
		BaseService service = App.getService("admin");
		service.sql("select a.*,b.gname,b.gdesc from {prefix}admin a left join {prefix}group b on a.gid=b.gid");
		List<HashMap<String, Object>> list = service.selectList();
		ModelAndView view=new ModelAndView("admin/frame/userManage","list",list);
		return view;
	}
	/*
	 * 处理新增和更新用户
	 */
	@RequestMapping("/add_user")
	public String add_user(String password,AdminBean admin) throws Exception{		 
		BaseService service = App.getService("admin");
		if(admin.getAid()!=0){	
			if(password.length()==32){
				service.where("aid=#{aid}")
				.setData(admin.getAname(),admin.getGid(),admin.getAid())
				.update("aname","gid");
			}else{	
				Encrypt encrypt=Encrypt.getEncrypt();
			    password=encrypt.md5(encrypt.md5(admin.getAname()+password));
			    admin.setPassword(password);
			    service.update(admin);
			}	
		}else{
			Encrypt encrypt=Encrypt.getEncrypt();
		    password=encrypt.md5(encrypt.md5(admin.getAname()+password));
		    admin.setPassword(password);
		    service.insert(admin);
		}
		return "local:manage_user";   	
	}
	/*
	 * 删除用户
	 */
	@RequestMapping("/delete_user")
	public String delete_user(int aid){
		BaseService service = App.getService("admin");
		service.deleteById(aid);
		return "local:manage_user";  
	}
	/*
	 * 用户登录
	 */
	@PermitPoll(type="all")
	@ResponseBody
	@RequestMapping("/login")
	public String login(AdminBean admin,HttpServletRequest request){	
		BaseService service=App.getService();
		Encrypt encrypt=Encrypt.getEncrypt();
		String password=encrypt.md5(encrypt.md5(admin.getAname()+admin.getPassword()));
		List<HashMap<String, Object>> list=service
				.sql("select a.*,b.oname,c.realName from {prefix}admin a left join {prefix}organization b on a.oid=b.oid left join {prefix}datainfo c on a.aid=c.outKey and c.table='laocheng_admin'")
				.where("a.aname=#{aname} and a.password=#{password}")
				.setData(admin.getAname(),password)
				.selectList();
		
		if(list.size()==1){		
			HttpSession session=request.getSession();
			Set<String> key_array=list.get(0).keySet();
			String key=new String();
            Iterator<String> it_1=key_array.iterator();
            while (it_1.hasNext()) {
				key=it_1.next();					
				if(key.equals("password")){
					continue;
				}else{
					Userinfo.putUserInfo(key, list.get(0).get(key), request);					
					session.setMaxInactiveInterval(3600);
					session.setAttribute(key, list.get(0).get(key));
				}							
			}    
            return "1";
		}else{
			return "0";
		}
	}	
	/*
	 * 用户退出
	 */
	@RequestMapping("/quit")
	public void quit(HttpServletRequest request,HttpServletResponse response) throws IOException{
		HttpSession session=request.getSession();
		Enumeration<String> names=session.getAttributeNames();
		while(names.hasMoreElements()){
			String name=names.nextElement();
			session.removeAttribute(name);
		}
		session=null;
		response.sendRedirect(Userinfo.getUserInfo("app_path", request)+"login.html");	
	} 
	/*
	 * 获得用户组的权限
	 */
	private List<HashMap<String, Object>> getGroupPermission(List<HashMap<String, Object>> list) {		
		for (int i = 0; i < list.size(); i++) {
			String per_str = (String) list.get(i).get("gpermission");
			String[] per_arr = per_str.split(",");
			String[] map = new String[per_arr.length];		
			for (int j = 0; j < per_arr.length; j++) {
				for(int m=0;m<Permission.PERMIT.size();m++){
					if((long)Permission.PERMIT.get(m).get("id")==Integer.valueOf(per_arr[j])){
						String name = (String)Permission.PERMIT.get(m).get("name");
						map[j]=name;
					}
				}			
			}
			list.get(i).put("gpermission", map);
		}
		return list;
	}
	/*
	 * 获得permission_action.xml和permission_tag.xml权限列表
	 */
	private Xmllist getPermissionList(){	
		BaseService service = App.getService("permit_action");	
		List<HashMap<String, Object>> list = service.where("type!='all'").selectList();
		return new Xmllist(list);
       
	}
	//实体对象，用于储存权限列表
	private class Xmllist{
		public  List<HashMap<String, Object>> permission_action;
		public  HashSet<String> permission_type_action;
		public Xmllist(List<HashMap<String, Object>> permission_action) {
			permission_type_action=new HashSet<String>();
			this.permission_action=permission_action;
			for(int i=0;i<permission_action.size();i++){
				permission_type_action.add((String)permission_action.get(i).get("type"));
			}			
		}		
	}
}
